package cn.hznc.controller.test;

import cn.hznc.aspect.BusinessType;
import cn.hznc.aspect.Log;
import cn.hznc.controller.program.strategy.AbutmentProgramContext;
import cn.hznc.controller.program.strategy.AbutmentProgramStrategy;
import cn.hznc.controller.program.strategy.ZccAbutmentProgramStrategy;
import cn.hznc.controller.service.codescanner.CodeScannerService;
import cn.hznc.controller.service.sharefile.ShareFileService;
import cn.hznc.domain.entity.ConfigurationEntity;
import cn.hznc.domain.entity.ToolParamCacheEntity;
import cn.hznc.domain.request.codescanner.SingleParamReq;
import cn.hznc.domain.request.codescanner.WriteParamsReq;
import cn.hznc.domain.response.ResponseBody;
import cn.hznc.exception.ToolManageException;
import cn.hznc.mapper.ConfigurationMapper;
import cn.hznc.mapper.ToolParamCacheMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * @Author：Administrator
 * @Date：2023/9/14 9:53
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@Slf4j
public class ShareFileController{
    @Autowired
    private ShareFileService shareFileService;

    @Autowired
    private CodeScannerService codeScannerService;

    @Resource
    private ConfigurationMapper configurationMapper;

    @Resource
    private ToolParamCacheMapper toolParamCacheMapper;

    @Resource
    private ZccAbutmentProgramStrategy zccAbutmentProgramStrategy;

    @RequestMapping(value = "/insertShareFile", method = RequestMethod.GET)
    //@Log(title = "同步共享文件程序信息" , businessType = BusinessType.INSERT)
    public ResponseBody insertShareFile() {
        AbutmentProgramContext abutmentProgramContext = new AbutmentProgramContext(zccAbutmentProgramStrategy);
        abutmentProgramContext.insertShareFile();
        //shareFileService.insertShareFile();
        return ResponseBody.success(Boolean.TRUE);
    }

    @RequestMapping(value = "/queryMachineToolProgram", method = RequestMethod.GET)
    public ResponseBody queryMachineToolProgram(@RequestParam("partno")String partno) {
        return ResponseBody.success(shareFileService.queryMachineToolProgram(partno));

    }

    @RequestMapping(value = "/queryMachineToolProgramGroup", method = RequestMethod.GET)
    public ResponseBody queryMachineToolProgramGroup(@RequestParam("partno")String partno , @RequestParam("pageNum")Integer pageNum,@RequestParam("pageSize")Integer pageSize) {
        return ResponseBody.success(shareFileService.queryMachineToolProgramGroup(partno,pageNum,pageSize));

    }

    @RequestMapping(value = "/getToolParam", method = RequestMethod.POST)
    public Boolean getToolParam(@RequestBody String toolParams) throws ParseException, InterruptedException, ToolManageException {
        try{
            ToolParamCacheEntity toolParamCacheEntity = new ToolParamCacheEntity();
            if (StringUtil.isNotEmpty(toolParams)) {
                String[] split = toolParams.split(",");
                toolParamCacheEntity.setToolNo("T" + split[0]);
                if(StringUtil.isNotEmpty(split[1])){
                    toolParamCacheEntity.setLength(Double.valueOf(split[1]));
                }
                if(StringUtil.isNotEmpty(split[2])){
                    toolParamCacheEntity.setRadius(Double.valueOf(split[2]));
                }
//            split[4] = split[4].replaceAll("T" , " ");
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date parse = sdf.parse(split[4]);
                QueryWrapper<ConfigurationEntity> retryWrapper = new QueryWrapper<>();
                retryWrapper.eq("configure_key", "retryTime");
                ConfigurationEntity retryTimeConfiguration = configurationMapper.selectOne(retryWrapper);
                Integer retryTime = Integer.valueOf(retryTimeConfiguration.getConfigureValue());
                //设置标志位
                Boolean flag = false;
                while (retryTime >0){
                    Map<String, String> readParams = codeScannerService.readParams("1", "http://192.168.32.109:33123", "COM3");
                    if(!readParams.getOrDefault("shankRfid" , "").equals("")){
                        flag = true;
                        break;
                    }
                    retryTime--;
                    Thread.sleep(1000);
                }
                toolParamCacheEntity.setCreateTime(new Date());
                toolParamCacheEntity.setSelectedFlag(0);
                QueryWrapper<ConfigurationEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("configure_key", "cycleTime");
                ConfigurationEntity configurationEntity = configurationMapper.selectOne(wrapper);
                Integer cycleTime = Integer.valueOf(configurationEntity.getConfigureValue());
                //能成功读取数据才进入循环写入数据并校验写入的数据和读取的数据是否一致
                while (cycleTime > 0 && flag) {
                    WriteParamsReq writeParamsReq = new WriteParamsReq();
                    writeParamsReq.setOperateType("1");
                    writeParamsReq.setUrl("http://192.168.32.109:33123");
                    writeParamsReq.setCom("COM3");
                    List<SingleParamReq> writeParams = new ArrayList<>();
                    //设置长度  半径
                    SingleParamReq lengthParam = new SingleParamReq();
                    lengthParam.setParam("长度");
                    lengthParam.setValue(split[1]);

                    SingleParamReq oalParam = new SingleParamReq();
                    oalParam.setParam("半径");
                    oalParam.setValue(split[2]);
                    writeParams.add(lengthParam);
                    writeParams.add(oalParam);
                    writeParamsReq.setWriteParams(writeParams);
                    if (codeScannerService.writeParams(writeParamsReq)) {
                        Map<String, String> readParams = codeScannerService.readParams("1", "http://192.168.32.109:33123", "COM3");
                        String length = readParams.getOrDefault("length", "");
                        String radius = readParams.getOrDefault("radius", "");
                        if (Objects.equals(length, split[1]) && Objects.equals(radius, split[2])) {
                            toolParamCacheEntity.setShankRfid(readParams.getOrDefault("shankRfid", ""));
                            break;
                        }
                    };

                    cycleTime--;
                    Thread.sleep(1000);
                }
            }
            //TO DO 处理时间
            toolParamCacheMapper.insert(toolParamCacheEntity);
            System.out.println("toolParams = " + toolParams);
            return Boolean.TRUE;
        }catch (Exception EX){
            System.out.println("toolParams = " + EX.toString());
            return Boolean.TRUE;
        }

    }


}
